<template>
  <div class="app-container">
    <!-- 页面标题和统计信息 -->
    <div class="page-header" data-aos="fade-down">
      <div class="page-title">
        <i class="el-icon-s-data"></i>
        <span>压力传感器数据管理</span>
      </div>
      <div class="page-description">
        实时监控和管理所有压力传感器数据，确保设备正常运行
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards" data-aos="fade-up" data-aos-delay="100">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card pressure-card normal-card">
          <div class="stats-icon pulse-animation" style="background-color: rgba(64, 158, 255, 0.1); color: #409EFF;">
            <i class="el-icon-s-data"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">平均压力值</div>
            <div class="stats-value">{{ averagePressure }} kPa</div>
            <div class="stats-desc">
              <span :class="pressureTrend > 0 ? 'trend-up' : pressureTrend < 0 ? 'trend-down' : 'trend-stable'">
                {{ pressureTrend > 0 ? '↑' : pressureTrend < 0 ? '↓' : '→' }} {{ Math.abs(pressureTrend) }}%
              </span>
              较上周期
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card pressure-card normal-card">
          <div class="stats-icon pulse-animation" style="background-color: rgba(103, 194, 58, 0.1); color: #67C23A;">
            <i class="el-icon-success"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">正常范围</div>
            <div class="stats-value">50-200 kPa</div>
            <div class="stats-desc">标准压力范围</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card pressure-card warning-card">
          <div class="stats-icon pulse-animation" style="background-color: rgba(230, 162, 60, 0.1); color: #E6A23C;">
            <i class="el-icon-warning"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">异常数据</div>
            <div class="stats-value">{{ abnormalCount }}</div>
            <div class="stats-desc">占比 {{ abnormalPercentage }}%</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card pressure-card normal-card">
          <div class="stats-icon pulse-animation" style="background-color: rgba(245, 108, 108, 0.1); color: #F56C6C;">
            <i class="el-icon-error"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">设备离线</div>
            <div class="stats-value">{{ offlineCount }}</div>
            <div class="stats-desc">活跃设备数量</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 压力趋势图表 -->
    <div class="chart-container" data-aos="fade-up" data-aos-delay="200">
      <div class="chart-header">
        <div class="chart-title">压力趋势分析</div>
        <div class="time-range-selector">
          <el-switch
            v-model="realTimeUpdate"
            active-text="实时更新"
            inactive-text="手动刷新"
            @change="handleRealTimeToggle"
          ></el-switch>
          <el-radio-group v-model="chartTimeRange" size="small">
            <el-radio-button label="1h">1小时</el-radio-button>
            <el-radio-button label="6h">6小时</el-radio-button>
            <el-radio-button label="1d">1天</el-radio-button>
            <el-radio-button label="7d">7天</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div ref="pressureChart" class="chart"></div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover" data-aos="fade-up" data-aos-delay="300">
      <div slot="header" class="card-header">
        <span><i class="el-icon-search"></i> 数据筛选</span>
        <el-button type="text" @click="showSearch = !showSearch">
          {{ showSearch ? '收起' : '展开' }}
          <i :class="showSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
        </el-button>
      </div>
      <el-collapse-transition>
        <div v-show="showSearch">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
            <el-form-item label="关联设备ID" prop="deviceId">
              <el-input
                v-model="queryParams.deviceId"
                placeholder="请输入关联设备ID"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="压力值范围" prop="pressureValue">
              <el-input
                v-model="queryParams.pressureValue"
                placeholder="请输入压力值(kPa)"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="压力区域" prop="positionZone">
              <el-select v-model="queryParams.positionZone" placeholder="请选择压力区域" clearable>
                <el-option label="区域A" value="A"></el-option>
                <el-option label="区域B" value="B"></el-option>
                <el-option label="区域C" value="C"></el-option>
                <el-option label="区域D" value="D"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据采集时间">
              <el-date-picker
                v-model="daterangeRecordTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="入库时间">
              <el-date-picker
                v-model="daterangeCreateTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card" shadow="hover" data-aos="fade-up" data-aos-delay="300">
      <div slot="header" class="card-header">
        <span><i class="el-icon-s-data"></i> 压力传感器数据</span>
        <div class="card-operations">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
            v-hasPermi="['system:pressureSensor:add']"
          >新增数据</el-button>
          <el-button
            type="success"
            icon="el-icon-edit"
            size="small"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:pressureSensor:edit']"
          >批量修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:pressureSensor:remove']"
          >批量删除</el-button>
          <el-button
            type="warning"
            icon="el-icon-download"
            size="small"
            @click="handleExport"
            v-hasPermi="['system:pressureSensor:export']"
          >导出数据</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="pressureSensorList" 
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        :cell-style="{padding: '8px 0'}"
        border
        stripe
        class="data-table"
        data-aos="fade-up" 
        data-aos-delay="500"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="记录ID" align="center" prop="id" width="80" sortable="custom" />
        <el-table-column label="设备ID" align="center" prop="deviceId" sortable="custom" width="120">
          <template slot-scope="scope">
            <span class="device-id">{{ scope.row.deviceId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="压力值" align="center" prop="pressureValue" sortable="custom" width="120">
          <template slot-scope="scope">
            <div class="pressure-display">
              <i :class="['el-icon-s-data', getPressureIconClass(scope.row.pressureValue)]"></i>
              <span :class="['pressure-value', getPressureClass(scope.row.pressureValue)]">{{ scope.row.pressureValue }} kPa</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="压力区域" align="center" prop="positionZone" width="100">
          <template slot-scope="scope">
            <el-tag :type="getZoneType(scope.row.positionZone)" size="small">{{ getZoneText(scope.row.positionZone) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" sortable="custom" width="100">
          <template slot-scope="scope">
            <el-tag :type="getPressureType(scope.row.pressureValue)" size="small">
              <i :class="['el-icon', getPressureStatusIcon(scope.row.pressureValue)]"></i>
              {{ getStatusText(scope.row.pressureValue) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="采集时间" align="center" prop="recordTime" sortable="custom" width="180">
          <template slot-scope="scope">
            <div class="time-display">
              <div class="date">{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</div>
              <div class="time">{{ parseTime(scope.row.recordTime, '{h}:{i}:{s}') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center" prop="createTime" sortable="custom" width="180">
          <template slot-scope="scope">
            <div class="time-display">
              <div class="date">{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</div>
              <div class="time">{{ parseTime(scope.row.createTime, '{h}:{i}:{s}') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:pressureSensor:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:pressureSensor:remove']"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改压力传感器数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="关联设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入关联设备ID" />
        </el-form-item>
        <el-form-item label="压力值(kPa)" prop="pressureValue">
          <el-input-number v-model="form.pressureValue" :precision="2" :step="0.1" :min="0" :max="1000" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="压力区域" prop="positionZone">
          <el-select v-model="form.positionZone" placeholder="请选择压力区域" style="width: 100%">
            <el-option label="区域A" value="A"></el-option>
            <el-option label="区域B" value="B"></el-option>
            <el-option label="区域C" value="C"></el-option>
            <el-option label="区域D" value="D"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据采集时间" prop="recordTime">
          <el-date-picker
            v-model="form.recordTime"
            type="datetime"
            placeholder="选择数据采集时间"
            style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 数据详情对话框 -->
    <el-dialog title="压力传感器数据详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ currentRow.id }}</el-descriptions-item>
        <el-descriptions-item label="设备ID">{{ currentRow.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="压力值">{{ currentRow.pressureValue }} kPa</el-descriptions-item>
        <el-descriptions-item label="压力区域">{{ getZoneText(currentRow.positionZone) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentRow.pressureValue)">{{ getStatusText(currentRow.pressureValue) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="数据采集时间">{{ parseTime(currentRow.recordTime) }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{ parseTime(currentRow.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPressureSensor, getPressureSensor, delPressureSensor, addPressureSensor, updatePressureSensor } from "@/api/system/pressureSensor";
import * as echarts from 'echarts';

export default {
  name: "PressureSensor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 压力传感器数据表格数据
      pressureSensorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 当前查看的行数据
      currentRow: {},
      // 压力区域时间范围
      daterangeRecordTime: [],
      // 压力区域时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        pressure: null,
        pressureStatus: null,
        zone: null,
        recordTime: null,
        orderByColumn: 'recordTime',
        isAsc: 'desc'
      },
  computed: {
    /** 计算平均压力值 */
    averagePressure() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      const sum = this.pressureSensorList.reduce((acc, item) => acc + parseFloat(item.pressure || item.pressureValue || 0), 0);
      return (sum / this.pressureSensorList.length).toFixed(1);
    },
    /** 计算正常数据数量 */
    normalCount() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      return this.pressureSensorList.filter(item => {
        const pressure = parseFloat(item.pressure || item.pressureValue || 0);
        return pressure >= 50 && pressure <= 200;
      }).length;
    },
    /** 计算异常数据数量 */
    abnormalCount() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      return this.pressureSensorList.filter(item => {
        const pressure = parseFloat(item.pressure || item.pressureValue || 0);
        return pressure < 50 || pressure > 200;
      }).length;
    },
    /** 计算设备数量 */
    deviceCount() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      const devices = new Set(this.pressureSensorList.map(item => item.deviceId));
      return devices.size;
    },
    /** 计算离线设备数量 */
    offlineCount() {
      return Math.max(0, this.deviceCount - Math.floor(this.deviceCount * 0.85)); // 假设85%在线率
    },
    /** 计算正常数据占比 */
    normalPercentage() {
      if (this.pressureSensorList.length === 0) return 0;
      return ((this.normalCount / this.pressureSensorList.length) * 100).toFixed(1);
    },
    /** 计算异常数据占比 */
    abnormalPercentage() {
      if (this.pressureSensorList.length === 0) return 0;
      return ((this.abnormalCount / this.pressureSensorList.length) * 100).toFixed(1);
    },
    /** 计算压力趋势 */
    pressureTrend() {
      // 模拟趋势数据，实际应用中应该从API获取
      return (Math.random() * 10 - 5).toFixed(1);
    }
  },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "关联设备ID不能为空", trigger: "blur" }
        ],
        pressureValue: [
          { required: true, message: "压力值不能为空", trigger: "blur" }
        ],
        positionZone: [
          { required: true, message: "压力区域不能为空", trigger: "change" }
        ],
        recordTime: [
          { required: true, message: "数据采集时间不能为空", trigger: "blur" }
        ]
      },
      // 图表时间范围
      chartTimeRange: '1d',
      // 图表实例
      chart: null,
      // 实时更新开关
      realTimeUpdate: false,
      // 实时更新定时器
      realTimeTimer: null,
      // 实时更新间隔(毫秒)
      realTimeInterval: 30000 // 30秒更新一次
    }
  },
  computed: {
    /** 计算平均压力值 */
    averagePressure() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      const sum = this.pressureSensorList.reduce((acc, item) => acc + parseFloat(item.pressure || item.pressureValue || 0), 0);
      return (sum / this.pressureSensorList.length).toFixed(1);
    },
    /** 计算正常数据数量 */
    normalCount() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      return this.pressureSensorList.filter(item => {
        const pressure = parseFloat(item.pressure || item.pressureValue || 0);
        return pressure >= 50 && pressure <= 200;
      }).length;
    },
    /** 计算异常数据数量 */
    abnormalCount() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      return this.pressureSensorList.filter(item => {
        const pressure = parseFloat(item.pressure || item.pressureValue || 0);
        return pressure < 50 || pressure > 200;
      }).length;
    },
    /** 计算设备数量 */
    deviceCount() {
      if (!this.pressureSensorList || this.pressureSensorList.length === 0) return 0;
      const devices = new Set(this.pressureSensorList.map(item => item.deviceId));
      return devices.size;
    },
    /** 计算离线设备数量 */
    offlineCount() {
      return Math.max(0, this.deviceCount - Math.floor(this.deviceCount * 0.85)); // 假设85%在线率
    },
    /** 计算正常数据占比 */
    normalPercentage() {
      if (this.pressureSensorList.length === 0) return 0;
      return ((this.normalCount / this.pressureSensorList.length) * 100).toFixed(1);
    },
    /** 计算异常数据占比 */
    abnormalPercentage() {
      if (this.pressureSensorList.length === 0) return 0;
      return ((this.abnormalCount / this.pressureSensorList.length) * 100).toFixed(1);
    },
    /** 计算压力趋势 */
    pressureTrend() {
      // 模拟趋势数据，实际应用中应该从API获取
      return (Math.random() * 10 - 5).toFixed(1);
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    window.removeEventListener('resize', this.handleResize)
    // 清理实时更新定时器
    this.stopRealTimeUpdate()
  },
  methods: {
    /** 查询压力传感器数据列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeRecordTime && '' != this.daterangeRecordTime) {
        this.queryParams.params["beginRecordTime"] = this.daterangeRecordTime[0]
        this.queryParams.params["endRecordTime"] = this.daterangeRecordTime[1]
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1]
      }
      listPressureSensor(this.queryParams).then(response => {
        this.pressureSensorList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        pressureValue: null,
        positionZone: null,
        recordTime: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRecordTime = []
      this.daterangeCreateTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加压力传感器数据"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPressureSensor(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改压力传感器数据"
      })
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      this.currentRow = row
      this.detailOpen = true
    },
    /** 查看设备详情 */
    viewDeviceDetails(deviceId) {
      this.$router.push({
        path: '/system/device',
        query: { deviceId: deviceId }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePressureSensor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPressureSensor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除压力传感器数据编号为"' + ids + '"的数据项？').then(function() {
        return delPressureSensor(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/pressureSensor/export', {
        ...this.queryParams
      }, `pressureSensor_${new Date().getTime()}.xlsx`)
    },
    /** 获取压力状态类型 */
    getPressureType(pressure) {
      const value = parseFloat(pressure);
      if (value < 50 || value > 200) return 'danger';
      if (value < 80 || value > 150) return 'warning';
      return 'success';
    },
    /** 获取区域类型 */
    getZoneType(zone) {
      const zoneMap = {
        'A': 'primary',
        'B': 'success',
        'C': 'warning',
        'D': 'danger'
      };
      return zoneMap[zone] || 'info';
    },
    /** 获取区域文本 */
    getZoneText(zone) {
      const zoneMap = {
        'A': '区域A',
        'B': '区域B',
        'C': '区域C',
        'D': '区域D'
      };
      return zoneMap[zone] || zone;
    },
    /** 获取状态类型 */
    getStatusType(pressure) {
      return this.getPressureType(pressure);
    },
    /** 获取状态文本 */
    getStatusText(pressure) {
      const value = parseFloat(pressure);
      if (value < 50 || value > 200) return '异常';
      if (value < 80 || value > 150) return '警告';
      return '正常';
    },
    /** 获取压力值样式类 */
    getPressureClass(pressure) {
      const value = parseFloat(pressure);
      if (value < 50 || value > 200) return 'pressure-danger';
      if (value < 60 || value > 180) return 'pressure-warning';
      return 'pressure-normal';
    },
    /** 获取压力图标样式类 */
    getPressureIconClass(pressure) {
      const value = parseFloat(pressure);
      if (value < 50 || value > 200) return 'pulse-danger';
      if (value < 60 || value > 180) return 'pulse-warning';
      return 'pulse-normal';
    },
    /** 获取压力状态图标 */
    getPressureStatusIcon(pressure) {
      const value = parseFloat(pressure);
      if (value < 50 || value > 200) return 'el-icon-warning';
      if (value < 60 || value > 180) return 'el-icon-info';
      return 'el-icon-success';
    },
    /** 初始化图表 */
    initChart() {
      if (!this.$refs.pressureChart) return;
      
      this.chart = echarts.init(this.$refs.pressureChart);
      this.updateChartData();
    },
    /** 处理实时更新开关 */
    handleRealTimeToggle(value) {
      if (value) {
        // 开启实时更新
        this.startRealTimeUpdate()
        this.$message({
          message: '已开启实时数据更新，每30秒刷新一次',
          type: 'success'
        })
      } else {
        // 关闭实时更新
        this.stopRealTimeUpdate()
        this.$message({
          message: '已关闭实时数据更新',
          type: 'info'
        })
      }
    },
    /** 开始实时更新 */
    startRealTimeUpdate() {
      // 清除可能存在的定时器
      this.stopRealTimeUpdate()
      
      // 设置新的定时器
      this.realTimeTimer = setInterval(() => {
        this.getList()
        this.updateChartData()
        
        // 显示更新提示
        this.$notify({
          title: '数据更新',
          message: '压力传感器数据已更新',
          type: 'success',
          duration: 2000,
          position: 'bottom-right'
        })
      }, this.realTimeInterval)
    },
    /** 停止实时更新 */
    stopRealTimeUpdate() {
      if (this.realTimeTimer) {
        clearInterval(this.realTimeTimer)
        this.realTimeTimer = null
      }
    },
    /** 更新图表数据 */
    updateChartData() {
      if (!this.chart) return;
      
      // 模拟数据，实际应用中应该从API获取
      const now = new Date();
      const data = [];
      const times = [];
      
      // 根据时间范围生成数据点
      let dataPoints = 24; // 默认1天24个点
      let timeFormat = '{h}:{i}';
      
      switch (this.chartTimeRange) {
        case '1h':
          dataPoints = 12;
          timeFormat = '{h}:{i}';
          break;
        case '6h':
          dataPoints = 18;
          timeFormat = '{h}:{i}';
          break;
        case '1d':
          dataPoints = 24;
          timeFormat = '{h}:{i}';
          break;
        case '7d':
          dataPoints = 7;
          timeFormat = '{m}-{d}';
          break;
      }
      
      // 生成模拟数据
      for (let i = dataPoints - 1; i >= 0; i--) {
        const time = new Date(now);
        
        if (this.chartTimeRange === '1h') {
          time.setMinutes(now.getMinutes() - i * 5);
        } else if (this.chartTimeRange === '6h') {
          time.setMinutes(now.getMinutes() - i * 20);
        } else if (this.chartTimeRange === '1d') {
          time.setHours(now.getHours() - i);
        } else if (this.chartTimeRange === '7d') {
          time.setDate(now.getDate() - i);
        }
        
        times.push(this.parseTime(time, timeFormat));
        
        // 生成随机压力数据，范围在50-200之间
        const basePressure = 125;
        const variation = Math.random() * 50 - 25;
        data.push(Math.round(basePressure + variation));
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].name}<br/>压力: ${params[0].value} kPa`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: times
        },
        yAxis: {
          type: 'value',
          min: 30,
          max: 220,
          axisLabel: {
            formatter: '{value} kPa'
          }
        },
        series: [
          {
            name: '压力',
            type: 'line',
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            },
            data: data,
            markLine: {
              data: [
                { yAxis: 50, name: '最低正常值' },
                { yAxis: 200, name: '最高正常值' }
              ],
              label: {
                formatter: '{b}'
              }
            }
          }
        ]
      };
      
      this.chart.setOption(option);
    },
    /** 处理窗口大小变化 */
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    /** 处理表格排序 */
    handleSortChange({ column, prop, order }) {
      this.queryParams.orderByColumn = prop;
      this.queryParams.isAsc = order === 'ascending';
      this.getList();
    }
  },
  watch: {
    chartTimeRange() {
      this.updateChartData();
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.page-header {
  margin-bottom: 20px;
  
  .page-title {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 10px;
    
    i {
      margin-right: 10px;
      color: #409EFF;
    }
  }
  
  .page-description {
    font-size: 14px;
    color: #606266;
    line-height: 1.5;
  }
}

.stats-cards {
  margin-bottom: 20px;
  
  .stats-card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    }
    
    .stats-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      
      i {
        font-size: 24px;
      }
    }
    
    .stats-content {
      flex: 1;
      
      .stats-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }
      
      .stats-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: none;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  }
}

.pressure-card {
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, #409EFF, #67C23A);
  }
  
  .card-icon {
    font-size: 24px;
    color: #409EFF;
    margin-right: 12px;
  }
  
  .card-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }
  
  .card-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }
  
  .card-desc {
    font-size: 12px;
    color: #C0C4CC;
  }
}

.normal-card {
  &::before {
    background: linear-gradient(to bottom, #67C23A, #409EFF);
  }
  
  .card-icon {
    color: #67C23A;
  }
}

.warning-card {
  &::before {
    background: linear-gradient(to bottom, #E6A23C, #F56C6C);
  }
  
  .card-icon {
    color: #E6A23C;
  }
}

.danger-card {
  &::before {
    background: linear-gradient(to bottom, #F56C6C, #E6A23C);
  }
  
  .card-icon {
    color: #F56C6C;
  }
}

.pulse-animation {
  display: inline-block;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.chart-container {
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .chart-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
    
    .time-range-selector {
      .el-radio-group {
        .el-radio-button__inner {
          padding: 8px 16px;
          font-size: 12px;
        }
      }
    }
  }
  
  .chart {
    height: 300px;
    width: 100%;
  }
}

.pressure-normal {
  color: #67C23A;
  font-weight: bold;
}

.pressure-warning {
  color: #E6A23C;
  font-weight: bold;
}

.pressure-danger {
  color: #F56C6C;
  font-weight: bold;
}

.pulse-normal {
  color: #67C23A;
  animation: pulse 2s infinite;
}

.pulse-warning {
  color: #E6A23C;
  animation: pulse 1.5s infinite;
}

.pulse-danger {
  color: #F56C6C;
  animation: pulse 1s infinite;
}

.device-id {
  font-family: 'Courier New', monospace;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.time-display {
  display: flex;
  flex-direction: column;
  
  .date {
    font-size: 12px;
    color: #909399;
  }
  
  .time {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
  }
}

.action-buttons {
  .el-button {
    margin-left: 5px;
    padding: 5px 8px;
    
    &.el-button--text {
      &:hover {
        background-color: rgba(64, 158, 255, 0.1);
      }
    }
  }
}

.pressure-display {
  display: flex;
  align-items: center;
  justify-content: center;
  
  i {
    margin-right: 5px;
  }
}

.trend-up {
  color: #F56C6C;
}

.trend-down {
  color: #409EFF;
}

.trend-stable {
  color: #909399;
}

.search-card, .table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    span {
      font-weight: 600;
      color: #303133;
      
      i {
        margin-right: 8px;
        color: #409EFF;
      }
    }
  }
  
  .card-operations {
    display: flex;
    gap: 10px;
  }
}

.el-table {
  margin-top: 0;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  ::v-deep .el-table__cell {
    padding: 8px 0;
  }
  
  ::v-deep .el-table th.el-table__cell {
    padding: 12px 0;
  }
  
  ::v-deep .el-table td.el-table__cell {
    border-right: none;
  }
  
  ::v-deep .el-table--border .el-table__cell {
    border-right: none;
  }
  
  ::v-deep .el-table--group::after, 
  ::v-deep .el-table--border::after, 
  ::v-deep .el-table::before {
    background-color: transparent;
  }
  
  .device-id {
    font-family: 'Courier New', monospace;
    background: #f5f7fa;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
  }
  
  .time-display {
    display: flex;
    flex-direction: column;
    
    .date {
      font-size: 12px;
      color: #909399;
    }
    
    .time {
      font-size: 13px;
      color: #606266;
      font-weight: 500;
    }
  }
  
  .action-buttons {
    .el-button {
      margin-left: 5px;
      padding: 5px 8px;
      transition: all 0.2s ease;
      
      &.el-button--text {
        &:hover {
          background-color: rgba(64, 158, 255, 0.1);
          transform: scale(1.1);
        }
      }
    }
  }
  
  .pressure-display {
    display: flex;
    align-items: center;
    justify-content: center;
    
    i {
      margin-right: 5px;
    }
  }
}

.el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

// 响应式布局
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }
  
  .stats-cards {
    .el-col {
      margin-bottom: 15px;
    }
  }
  
  .card-operations {
    flex-direction: column;
    gap: 5px;
  }
}
</style>